package com.lanou.moving.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.lanou.moving.R;
import com.lanou.moving.adapter.RankingListDetailAdapter;
import com.lanou.moving.base.BaseActivity;
import com.lanou.moving.base.BaseApplication;
import com.lanou.moving.constant.URL;
import com.lanou.moving.entity.MusicInfo;
import com.lanou.moving.entity.RankingListDetail;
import com.lanou.moving.entity.dao.AddTo;
import com.lanou.moving.entity.dao.AddToDao;
import com.lanou.moving.entity.dao.Collection;
import com.lanou.moving.entity.dao.CollectionDao;
import com.lanou.moving.entity.dao.RecentlyPlay;
import com.lanou.moving.entity.dao.RecentlyPlayDao;
import com.lanou.moving.eventBus.MyEventBus;
import com.lanou.moving.service.DownloadServices;
import com.lanou.moving.singleton.DaoSingleton;
import com.lanou.moving.view.CDSPopupWindow;
import com.lanou.moving.view.CommonProgressDialog;
import com.lanou.moving.volley.StringRequestUtf;
import com.lanou.moving.volley.VolleySingleton;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import it.sephiroth.android.library.picasso.Picasso;

/**
 * Created by dllo on 15/10/23.
 */
public class RankingListDetailActivity extends BaseActivity implements
        View.OnClickListener, AdapterView.OnItemClickListener, RankingListDetailAdapter.OnMenuClickListener {

    private CollapsingToolbarLayout toolbarLayout;
    private VolleySingleton volleySingleton;
    private StringRequestUtf request;
    // 网址拼接
    private int ranklist_id;// 变化的参数
    private String title;// toolBar的title
    // 背景图片
    private RankingListDetail.ImageEntity image;
    private ImageView songs_list_bg;
    // 歌曲
    private ListView songs_list_listview;
    private List<RankingListDetail.SongsEntity> songsEntities;
    private RankingListDetailAdapter adapter;
    private Toolbar coordinator_toolbar;
    private TextView songs_list_collection;
    private RankingListDetail data;
    private AddToDao addToDao;//数据库表
    //数据库表
    private CollectionDao collectionDao;
    private RecentlyPlayDao recentlyPlayDao;
    private View view;
    private TextView collect_tv;
    private ImageView rankingListBackground;
    private List<Collection> collections;
    private CDSPopupWindow pw;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ranking_list_detail);
        BaseApplication.getInstance().addActivity(this);
        addToDao = DaoSingleton.getInstance().getAddToDao();
        collectionDao = DaoSingleton.getInstance().getCollectionDao();
        recentlyPlayDao = DaoSingleton.getInstance().getRecentlyPlayDao();
        ranklist_id = getIntent().getIntExtra("ranklist_id", 0);
        initView();
        getData();
    }

    private void initView() {
        volleySingleton = VolleySingleton.getInstance(this);
//        Toolbar toolbar = (Toolbar) findViewById(R.id.coordinator_toolbar);
//        setSupportActionBar(toolbar);
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        view = LayoutInflater.from(this).inflate(R.layout.layout_song, null);
        collect_tv = (TextView) view.findViewById(R.id.layout_song_collection);
        rankingListBackground = (ImageView) findViewById(R.id.new_song_background);

        toolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        songs_list_bg = (ImageView) findViewById(R.id.songs_list_bg);
        songs_list_listview = (ListView) findViewById(R.id.songs_list_listview);
        songs_list_listview.setOnItemClickListener(this);

        coordinator_toolbar = (Toolbar) findViewById(R.id.coordinator_toolbar);
        coordinator_toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        songs_list_collection = (TextView) findViewById(R.id.songs_list_collection);
        songs_list_collection.setOnClickListener(this);
    }


    private void getData() {
        String url = URL.RANKING_LIST_DETAIL_START + ranklist_id + URL.RANKING_LIST_DETAIL_END;
        request = new StringRequestUtf(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                data = gson.fromJson(response, RankingListDetail.class);
                title = data.getTitle();
                image = data.getImage();
                songsEntities = data.getSongs();
                adapter = new RankingListDetailAdapter(RankingListDetailActivity.this, songsEntities);
                adapter.setOnMenuClickListener(RankingListDetailActivity.this);
                songs_list_listview.setAdapter(adapter);

                Picasso.with(RankingListDetailActivity.this).load(image.getPic())
                        .placeholder(R.mipmap.songlist_cover).error(R.mipmap.songlist_cover).into(songs_list_bg);
                toolbarLayout.setTitle(title);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        volleySingleton.addQueue(request);
    }

    @Override
    protected void onResume() {
        super.onResume();
        List<AddTo> lists = addToDao.queryBuilder().where(AddToDao.Properties.SongListId.eq(ranklist_id)).list();
        if (lists != null && lists.size() > 0) {
            songs_list_collection.setText("取消收藏");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.songs_list_collection:
                if ("收藏".equals(songs_list_collection.getText())) {
                    AddTo addTo = new AddTo();
                    addTo.setName(title);
                    addTo.setSongListId(ranklist_id);
                    addTo.setPicUrl(image.getPic());
                    addTo.setSongs(data.getSongs().size());
                    addTo.setResource("排行榜");
                    addToDao.insert(addTo);
                    songs_list_collection.setText("取消收藏");
                    Toast.makeText(this, "已加入收藏", Toast.LENGTH_LONG).show();
                } else if ("取消收藏".equals(songs_list_collection.getText())) {
                    addToDao.queryBuilder().where(AddToDao.Properties.SongListId.eq(ranklist_id)).buildDelete()
                            .executeDeleteWithoutDetachingEntities();
                    songs_list_collection.setText("收藏");
                }
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        RankingListDetail.SongsEntity songsEntity = (RankingListDetail.SongsEntity) parent.getItemAtPosition(position);
        if (!(songsEntity.getUrlList() != null && songsEntity.getUrlList().size() > 0)) {
            Toast.makeText(this, "暂时无法播放此歌曲", Toast.LENGTH_LONG).show();
        } else {
            RecentlyPlay recentlyPlay = new RecentlyPlay();
            recentlyPlay.setSongName(songsEntity.getName());
            recentlyPlay.setPlayUrl(songsEntity.getUrlList().get(0).getUrl());
            recentlyPlay.setDuration(songsEntity.getUrlList().get(0).getDuration());
            recentlyPlay.setSingerName(songsEntity.getSingerName());
            recentlyPlay.setSongId(songsEntity.getSongId());
            recentlyPlay.setResource("网络");
            recentlyPlayDao.insertOrReplace(recentlyPlay);

            List<MusicInfo> musicInfoList = new ArrayList<>();
            for (RankingListDetail.SongsEntity entity : songsEntities) {
                if (entity.getUrlList() != null && entity.getUrlList().size() > 0) {
                    MusicInfo musicInfo = new MusicInfo();
                    musicInfo.setSongName(entity.getName());
                    musicInfo.setAlbum(entity.getAlbumName());
                    musicInfo.setAlbumId((int) entity.getAlbumId());
                    musicInfo.setDuration(entity.getUrlList().get(0).getDuration());
                    musicInfo.setUrl(entity.getUrlList().get(0).getUrl());
                    musicInfo.setSingerName(entity.getSingerName());
                    musicInfo.setResouce("网络");
                    musicInfoList.add(musicInfo);
                }
            }

            Intent intent = new Intent(RankingListDetailActivity.this, PlayMusicActivity.class);
//            intent.putExtra("songName",songsEntity.getName());
//            intent.putParcelableArrayListExtra("musicInfoList", (ArrayList<? extends Parcelable>) musicInfoList);
            EventBus.getDefault().post(new MyEventBus.Deliver(musicInfoList, songsEntity.getName()));
            intent.putExtra("songName", songsEntity.getName());
            intent.putExtra("duration", songsEntity.getUrlList().get(0).getDuration());
            intent.putExtra("albumId", songsEntity.getAlbumId());
            intent.putExtra("resource", "网络");
            intent.putExtra("singerName", songsEntity.getSingerName());
            startActivity(intent);
        }
    }

    @Override
    public void onMenuClick(final RankingListDetail.SongsEntity songsEntity) {
        rankingListBackground.setVisibility(View.VISIBLE);
        collections = collectionDao.queryBuilder().where(
                CollectionDao.Properties.SongId.eq(songsEntity.getSongId())).list();
        if (collections != null && collections.size() > 0) {
            collect_tv.setText("取消收藏");
        } else {
            collect_tv.setText("收藏");
        }
        pw = new CDSPopupWindow(this, view, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.layout_song_collection:
                        if ("收藏".equals(collect_tv.getText())) {
                            Collection collection = new Collection();
                            collection.setSongId((int) songsEntity.getSongId());
                            collection.setSongName(songsEntity.getName());
                            collection.setPlayUrl(songsEntity.getUrlList().get(0).getUrl());
                            collection.setAlbumId((int) songsEntity.getAlbumId());
                            collection.setDuration(songsEntity.getUrlList().get(0).getDuration());
                            collection.setSingerName(songsEntity.getSingerName());
                            collectionDao.insert(collection);
                            collect_tv.setText("取消收藏");
                            Toast.makeText(RankingListDetailActivity.this, "已收藏", Toast.LENGTH_LONG).show();
                            pw.dismiss();
                        } else if ("取消收藏".equals(collect_tv.getText())) {
                            collectionDao.queryBuilder().where(CollectionDao.Properties.SongId
                                    .eq(songsEntity.getSongId())).buildDelete()
                                    .executeDeleteWithoutDetachingEntities();
                            collect_tv.setText("收藏");
                            Toast.makeText(RankingListDetailActivity.this, "已取消收藏", Toast.LENGTH_LONG).show();
                            pw.dismiss();
                        }
                        break;
                    case R.id.layout_song_download:
                        if (songsEntity.getAuditionList() == null ||
                                songsEntity.getAuditionList().size() == 0 ||
                                songsEntity.getAuditionList().size() == 1) {
                            Toast.makeText(RankingListDetailActivity.this, "暂无资源", Toast.LENGTH_LONG).show();

                        } else if (songsEntity.getAuditionList().size() > 1){
                            String download_url = songsEntity.getAuditionList().get(1).getUrl();
                            Intent intent = new Intent(RankingListDetailActivity.this, DownloadServices.class);
                            intent.putExtra("url", download_url);
                            intent.putExtra("singerName", songsEntity.getSingerName());
                            intent.putExtra("songName", songsEntity.getName());
                            intent.putExtra("NotifyId", 0);
                            startService(intent);
                            pw.dismiss();
                        }
                        break;
                    case R.id.layout_song_share:
                        break;
                }

            }
        }, rankingListBackground);
        pw.showAtLocation(findViewById(R.id.coordinator_layout), Gravity.CENTER, 0, 0);
    }
}
